/**
 * 用户个人资料页面组件
 * 显示用户的学习进度、成就、统计数据和设置选项
 * 包含经验值、等级、连续学习天数、完成的课程数量等信息
 * 提供设置功能和数据重置选项
 */
import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  Dimensions
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import * as Progress from 'react-native-progress';

// 导入存储工具函数，用于获取和管理用户数据
import { 
  getUserProgress,    // 获取用户学习进度数据
  getAchievements,    // 获取用户成就数据
  resetProgress       // 重置用户学习进度
} from '../utils/storage';
import {
  AppCard,
  StatusIndicator,
  LoadingIndicator,
  Tag,
  AppButton
} from '../components/CommonUI';
import { NumberUtils, DateUtils } from '../utils/CommonUtils';
import { ProfileHeader } from '../components/Headers';
import { 
  StatisticsGrid, 
  AchievementsList, 
  SettingsMenu 
} from '../components/ScreenComponents';

// 获取屏幕宽度，用于响应式布局
const { width } = Dimensions.get('window');

/**
 * 用户个人资料页面主组件
 * 管理和显示用户的学习数据、成就和设置选项
 * @param {Object} navigation - React Navigation 导航对象，用于页面间跳转
 */
export default function ProfileScreen({ navigation }) {
  // 用户学习进度数据状态，包含所有关键学习指标
  const [userProgress, setUserProgress] = useState({
    totalXP: 0,           // 总经验值
    currentStreak: 0,     // 当前连续学习天数
    longestStreak: 0,     // 最长连续学习天数
    level: 1,             // 当前等级
    lessonsCompleted: 0,  // 已完成课程数
    totalLessons: 5       // 总课程数
  });
  // 用户成就数据状态，存储所有已解锁和未解锁的成就
  const [achievements, setAchievements] = useState([]);
  // 加载状态，用于显示加载中的界面
  const [loading, setLoading] = useState(true);

  // 组件加载时调用，加载用户数据
  useEffect(() => {
    loadProfileData();
  }, []);

  // 添加焦点监听器，当页面获得焦点时刷新数据
  // 这确保了当用户从其他页面返回时，数据会自动更新
  useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      loadProfileData();
    });

    // 组件卸载时清理监听器，防止内存泄漏
    return unsubscribe;
  }, [navigation]);

  /**
   * 加载用户个人资料数据
   * 从存储中获取用户的学习进度和成就数据
   * 包括错误处理和加载状态管理
   */
  const loadProfileData = async () => {
    try {
      // 并行获取用户进度和成就数据，提高加载效率
      const progress = await getUserProgress();
      const achievementsData = await getAchievements();
      
      // 更新组件状态
      setUserProgress(progress);
      setAchievements(achievementsData);
    } catch (error) {
      // 记录错误日志并向用户显示友好的错误信息
      console.error('加载个人资料数据错误:', error);
      Alert.alert('错误', '无法加载个人资料数据');
    } finally {
      // 无论成功还是失败，都要结束加载状态
      setLoading(false);
    }
  };

  /**
   * 处理重置学习进度操作
   * 显示确认对话框，防止用户意外操作
   * 重置后会清空所有学习数据和成就
   */
  const handleResetProgress = () => {
    Alert.alert(
      '重置学习进度',
      '你确定要重置所有学习进度吗？此操作不可撤销。',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '重置',
          style: 'destructive',
          onPress: async () => {
            try {
              // 执行重置操作并重新加载数据
              await resetProgress();
              await loadProfileData();
              Alert.alert('成功', '你的学习进度已重置。');
            } catch (error) {
              Alert.alert('错误', '重置进度失败。');
            }
          }
        }
      ]
    );
  };

  const getXPForNextLevel = () => {
    return userProgress.level * 100;
  };

  const getCurrentLevelXP = () => {
    return userProgress.totalXP % 100;
  };

  // 删除原有的renderStatCard和renderAchievement函数，因为现在使用组件化方式

  // 准备统计数据结构
  const statisticsData = [
    {
      icon: 'star',
      title: '总经验值',
      value: NumberUtils.formatWithCommas(userProgress.totalXP),
      subtitle: null,
      color: '#FFD700'
    },
    {
      icon: 'flame',
      title: '当前连续',
      value: userProgress.currentStreak.toString(),
      subtitle: '天',
      color: '#FF6B35'
    },
    {
      icon: 'trophy',
      title: '最长连续',
      value: userProgress.longestStreak.toString(),
      subtitle: '天',
      color: '#9C27B0'
    },
    {
      icon: 'book',
      title: '已完成课程',
      value: userProgress.lessonsCompleted.toString(),
      subtitle: `共 ${userProgress.totalLessons} 个`,
      color: '#2196F3'
    }
  ];

  // 准备设置菜单数据
  const settingsMenuItems = [
    {
      id: 'notifications',
      icon: 'notifications-outline',
      title: '通知设置',
      showChevron: true
    },
    {
      id: 'language',
      icon: 'language-outline',
      title: '语言设置',
      showChevron: true
    },
    {
      id: 'help',
      icon: 'help-circle-outline',
      title: '帮助与支持',
      showChevron: true
    },
    {
      id: 'reset',
      icon: 'refresh-outline',
      title: '重置学习进度',
      textColor: '#F44336',
      showChevron: true
    }
  ];

  // 处理设置菜单点击
  const handleSettingsItemPress = (item) => {
    if (item.id === 'reset') {
      handleResetProgress();
    } else {
      // 其他设置项的处理逻辑
      console.log(`点击了设置项: ${item.title}`);
    }
  };

  if (loading) {
    return (
      <SafeAreaView style={styles.loadingContainer}>
        <LoadingIndicator text="加载个人资料中..." />
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView showsVerticalScrollIndicator={false}>
        {/* 使用新的ProfileHeader组件 */}
        <ProfileHeader
          username="语言学习者"
          level={userProgress.level}
          currentLevelXP={getCurrentLevelXP()}
          nextLevelXP={100}
          onSettingsPress={() => console.log('点击设置')}
        />

        {/* 使用新的StatisticsGrid组件 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>统计数据</Text>
          <StatisticsGrid statistics={statisticsData} />
        </View>

        {/* 使用新的AchievementsList组件 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>成就</Text>
          <AchievementsList 
            achievements={achievements} 
            onAchievementPress={(achievement) => {
              console.log('点击成就:', achievement.title);
            }}
          />
        </View>

        {/* 使用新的SettingsMenu组件 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>设置</Text>
          <SettingsMenu 
            menuItems={settingsMenuItems}
            onItemPress={handleSettingsItemPress}
          />
        </View>

        <View style={styles.bottomPadding} />
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  header: {
    backgroundColor: '#58CC02',
    padding: 20,
    borderBottomLeftRadius: 25,
    borderBottomRightRadius: 25,
  },
  profileSection: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  avatarContainer: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: 'rgba(255,255,255,0.2)',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 20,
  },
  profileInfo: {
    flex: 1,
  },
  username: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 5,
  },
  levelText: {
    fontSize: 16,
    color: '#fff',
    opacity: 0.9,
  },
  levelProgressContainer: {
    marginTop: 10,
  },
  levelProgressHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  levelProgressText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '500',
  },
  xpText: {
    color: '#fff',
    fontSize: 14,
    opacity: 0.9,
  },
  section: {
    padding: 20,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 15,
  },
  statsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  statCard: {
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 15,
    width: (width - 60) / 2,
    marginBottom: 15,
    flexDirection: 'row',
    alignItems: 'center',
    elevation: 3,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
  },
  statIcon: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 10,
  },
  statContent: {
    flex: 1,
  },
  statValue: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
  },
  statTitle: {
    fontSize: 12,
    color: '#666',
    marginTop: 2,
  },
  statSubtitle: {
    fontSize: 10,
    color: '#999',
  },
  achievementCard: {
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 20,
    marginBottom: 15,
    flexDirection: 'row',
    alignItems: 'center',
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
    opacity: 0.6,
  },
  unlockedAchievement: {
    opacity: 1,
    borderColor: '#4CAF50',
    borderWidth: 2,
  },
  achievementIcon: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: '#f0f0f0',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 15,
  },
  unlockedIcon: {
    backgroundColor: '#E8F5E8',
  },
  achievementEmoji: {
    fontSize: 24,
  },
  achievementContent: {
    flex: 1,
  },
  achievementTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#999',
    marginBottom: 5,
  },
  unlockedTitle: {
    color: '#333',
  },
  achievementDescription: {
    fontSize: 14,
    color: '#999',
  },
  unlockedDescription: {
    color: '#666',
  },
  unlockedDate: {
    fontSize: 12,
    color: '#4CAF50',
    marginTop: 5,
    fontStyle: 'italic',
  },
  checkmarkContainer: {
    marginLeft: 10,
  },
  settingItem: {
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 20,
    marginBottom: 10,
    flexDirection: 'row',
    alignItems: 'center',
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  settingText: {
    flex: 1,
    fontSize: 16,
    color: '#333',
    marginLeft: 15,
  },
  bottomPadding: {
    height: 20,
  },
});